package com.example.skudemo.controller;


import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.ObjectUtil;
import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.example.skudemo.model.SkuEntity;
import com.example.skudemo.model.SpuEntity;
import com.example.skudemo.service.ISkuService;
import com.example.skudemo.service.ISpuService;
import com.example.skudemo.utils.ApiResult;
import com.example.skudemo.vo.SpuSkuVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;

import org.springframework.web.bind.annotation.RestController;

import javax.validation.Valid;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * <p>
 * 商品sku表 前端控制器
 * </p>
 *
 * @author 水痕
 * @since 2023-11-17
 */
@RestController
@Validated
@RequestMapping("/sku")
public class SkuController {
    @Autowired
    private ISpuService spuService;

    @Autowired
    private ISkuService skuService;

    @GetMapping("{spuId}")
    public ApiResult getSkuBySpuIdApi(@PathVariable @Valid Integer spuId) {
        // 1.根据spu获取商品属性
        LambdaQueryWrapper<SpuEntity> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(SpuEntity::getId, spuId);
        SpuEntity spuEntity = this.spuService.getOne(queryWrapper);
        // 2.根据spu查询全部的sku
        LambdaQueryWrapper<SkuEntity> queryWrapper1 = new LambdaQueryWrapper<>();
        queryWrapper1.eq(SkuEntity::getSpuId, spuId);
        List<SkuEntity> skuEntityList = this.skuService.list(queryWrapper1);
//        Map<String, SpuSkuVO> skuEntityMap = skuEntityList.stream().collect(Collectors.toMap(SkuEntity::getAttributeValue, p -> BeanUtil.copyProperties(p, SpuSkuVO.class)));
        Map<String, Object> resultMap = new HashMap<>();
        resultMap.put("skuAttribute", !ObjectUtil.isNull(spuEntity.getAttribute()) ? JSON.parse(spuEntity.getAttribute()) : null);
        resultMap.put("skuList", skuEntityList);
        return ApiResult.success(resultMap);
    }
}
